package tld.course.homework1 
{
	/**
	 * ...
	 * @author wvxvw
	 */
	public class Grid
	{
		private static const WINS:Vector.<uint> =
			new <uint>[
				0, 1, 2, 
				3, 4, 5, 
				6, 7, 8,
				0, 3, 6, 
				1, 4, 7, 
				2, 5, 8,
				0, 4, 8, 
				2, 4, 6
			];
		
		private const _cells:Vector.<String> = 
			new <String>["", "", "", "", "", "", "", "", ""];
		
		public function Grid() { super(); }
		
		public function get(x:uint, y:uint):String
		{
			return this._cells[x * 3 + y];
		}
		
		public function set(x:uint, y:uint, cell:String):void
		{
			this._cells[x * 3 + y] = cell;
		}
		
		public function getItem(position:uint):String
		{
			return this._cells[position];
		}
		
		public function setItem(position:uint, value:String):void
		{
			this._cells[position] = value;
		}
		
		public function get indexOf():Function { return this._cells.indexOf; }
		
		/**
		 * There is a defect in this function. When there are two winning 
		 * sequences simultaneously present on the board, it will find only
		 * the first one. 
		 * TODO: alter the function in a way it will find all winning sequences.
		 * example -
		 * X O X | X X O
		 * O X O | X X O
		 * X O X | O O O
		 * 
		 * @return vecror of positions of of the winning cells, where positions
		 * are arranged like so:
		 * 0 1 2
		 * 3 4 5
		 * 6 7 8
		 */
		public function winner():Vector.<uint>
		{
			var first:String;
			var second:String;
			var third:String;
			var result:Vector.<uint>;
			var i:int;
			
			for (var offset:uint; offset < 24; offset += 3)
			{
				first = this._cells[WINS[offset]];
				if (first)
				{
					second = this._cells[WINS[offset + 1]];
					if (second == first)
					{
						third = this._cells[WINS[offset + 2]];
						if (third == second)
						{
							if (!result)
							{
								result = 
									new <uint>[
										WINS[offset], 
										WINS[offset + 1], 
										WINS[offset + 2]
									];
							}
							else
							{
								i = 3;
								while (i--)
								{
									if (result.indexOf(WINS[offset + i]) < 0)
										result.push(WINS[offset + i]);
								}
							}
						}
					}
				}
			}
			return result;
		}
		
		public function clean():void
		{
			this._cells.splice(
				0, this._cells.length, "", "", "", "", "", "", "", "", "");
		}
	}
}